<script setup>
import { ref, computed, onMounted, watch, onBeforeUnmount } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '../stores/user'
import { useInventoryStore } from '../stores/inventory'
import { useItemsStore } from '../stores/items'
import { useNotificationStore } from '../stores/notification'
import { usePermissionStore } from '../stores/permission' // 导入权限store
import { locationsApi } from '../utils/apiService' // 引入API服务
import { Location, ArrowDown, Menu as IconMenu, Document, Goods, DataLine, Setting, ArrowRight, ArrowLeft, Plus, Search, Close, Bell, User } from '@element-plus/icons-vue' // 引入图标
import { ElMessage, ElMessageBox } from 'element-plus' // 引入消息组件和对话框组件
import NotificationBadge from '../components/notification/NotificationBadge.vue' // 导入消息通知组件

const router = useRouter()
const userStore = useUserStore()
const inventoryStore = useInventoryStore()
const itemsStore = useItemsStore()
const notificationStore = useNotificationStore()
const permissionStore = usePermissionStore() // 添加权限store

const isCollapse = ref(false)
const activeMenu = ref('home')
const showDetails = ref(false)
const selectedItem = ref(null)
const searchQuery = ref('')

// --- 位置选择器状态 ---
const showLocationSelector = ref(false)
const appLocations = ref([]) // 初始为空数组，将从API获取
const selectedLocationId = ref(null) // 默认不选中
const locationsLoading = ref(false) // 添加加载状态

const currentLocationName = computed(() => {
  // 首先从内存中的位置列表查找
  const loc = appLocations.value.find(l => String(l.id) === String(selectedLocationId.value));
  if (loc) {
    console.log('从内存中找到位置名称:', loc.name);
    return loc.name;
  }
  
  // 如果内存中没有找到，尝试从localStorage获取
  try {
    const storedLocations = JSON.parse(localStorage.getItem('userLocations') || '[]');
    const storedLoc = storedLocations.find(l => String(l.id) === String(selectedLocationId.value));
    if (storedLoc) {
      console.log('从localStorage获取到位置名称:', storedLoc.name);
      return storedLoc.name;
    }
  } catch (error) {
    console.error('从localStorage获取位置信息失败:', error);
  }
  
  return '选择位置';
})

// 获取用户位置
const fetchUserLocations = async () => {
  try {
    locationsLoading.value = true
    
    // 首先尝试从URL查询参数获取locationId
    const locationIdFromUrl = router.currentRoute.value.query.locationId;
    console.log('fetchUserLocations: 从URL获取位置ID:', locationIdFromUrl, '类型:', typeof locationIdFromUrl);
    
    if (locationIdFromUrl) {
      console.log('fetchUserLocations: 设置从URL获取的位置ID:', locationIdFromUrl);
      // 确保位置ID是字符串形式保存，统一处理
      selectedLocationId.value = String(locationIdFromUrl);
      localStorage.setItem('currentLocationId', String(locationIdFromUrl));
    } else {
      // 如果URL中没有，尝试从localStorage获取
      const savedLocationId = localStorage.getItem('currentLocationId');
      if (savedLocationId) {
        console.log('fetchUserLocations: 从localStorage获取位置ID:', savedLocationId);
        selectedLocationId.value = savedLocationId;
      }
    }
    
    // 获取当前用户ID和用户名
    console.log('获取用户信息', userStore.getUser)
    
    // 直接从localStorage获取用户信息作为备选方案
    let userId = userStore.getUser?.id
    let username = userStore.getUser?.name || userStore.getUser?.username
    
    // 如果从store获取不到，尝试从localStorage获取
    if (!userId) {
      try {
        const userJson = localStorage.getItem('user')
        if (userJson && userJson !== 'undefined') {
          const userData = JSON.parse(userJson)
          userId = userData.id
          username = userData.name || userData.username || '用户'
          console.log('从localStorage获取到用户信息', userData)
        } else if (userJson === 'undefined') {
          console.warn('localStorage中的用户信息是无效的 "undefined" 字符串')
          localStorage.removeItem('user') // 清除无效数据
        }
      } catch (err) {
        console.error('解析localStorage中的用户信息失败', err)
      }
    }
    
    if (!userId) {
      console.error('未找到用户ID，无法获取位置信息')
      return
    }
    
    console.log('即将发送位置查询请求，用户ID:', userId, '用户名:', username)
    
    // 调用API获取用户位置
    const response = await locationsApi.getUserLocations(userId)
    console.log('获取用户位置响应:', response)
    
    // 处理响应数据
    if (response && response.code === 200 && response.data) {
      // 直接使用API返回的位置数据，不再创建默认位置
      appLocations.value = response.data
      
      // 将位置信息保存到localStorage
      localStorage.setItem('userLocations', JSON.stringify(appLocations.value))
      
      console.log('获取到位置数据:', appLocations.value.length, '个位置');
      
      // 如果有位置，默认选中第一个
      if (appLocations.value.length > 0 && !selectedLocationId.value) {
        selectedLocationId.value = String(appLocations.value[0].id)
        console.log('未选中位置，设置第一个位置:', selectedLocationId.value);
        
        // 将默认选择的位置ID添加到路由参数中
        const currentRoute = router.currentRoute.value;
        router.replace({ 
          path: currentRoute.path, 
          query: { ...currentRoute.query, locationId: selectedLocationId.value } 
        });
        
        // 同时也保存到localStorage作为后备
        localStorage.setItem('currentLocationId', selectedLocationId.value);
      } else if (selectedLocationId.value) {
        // 如果已有选择的位置ID，打印调试信息
        console.log('已有选中的位置ID:', selectedLocationId.value, 
                   '当前位置名称:', currentLocationName.value);
                   
        // 检查是否能找到匹配的位置
        const matchedLocation = appLocations.value.find(
          l => String(l.id) === String(selectedLocationId.value)
        );
        console.log('匹配的位置:', matchedLocation ? matchedLocation.name : '未找到');
        
        // 确保URL参数同步
        const currentRoute = router.currentRoute.value;
        if (currentRoute.query?.locationId !== selectedLocationId.value) {
          router.replace({ 
            path: currentRoute.path, 
            query: { ...currentRoute.query, locationId: selectedLocationId.value } 
          });
        }
      }
    } else {
      console.error('获取用户位置失败:', response)
      ElMessage.warning('获取位置信息失败，请手动添加位置')
    }
  } catch (error) {
    console.error('获取用户位置出错:', error)
    ElMessage.error('无法连接到服务器，获取位置信息失败')
  } finally {
    locationsLoading.value = false
  }
}

const toggleLocationSelector = () => {
  showLocationSelector.value = !showLocationSelector.value
}

const selectLocation = (locationId) => {
  selectedLocationId.value = String(locationId)
  showLocationSelector.value = false
  
  // 保存到localStorage，确保是字符串格式
  if (locationId) {
    localStorage.setItem('currentLocationId', String(locationId));
    console.log('位置ID已保存到localStorage:', String(locationId));
  } else {
    localStorage.removeItem('currentLocationId');
    console.log('已从localStorage移除位置ID');
  }
  
  // 检查用户在此位置的权限
  const userPermission = permissionStore.getUserRoleForLocation(locationId);
  console.log(`已选择位置 ${locationId}，用户权限:`, userPermission);
  
  // 如果当前路径是权限管理，但用户没有权限查看，则跳转回主页
  if (router.currentRoute.value.path.includes('/permissions') && 
      !permissionStore.canViewUserPermissions(locationId)) {
    ElMessage.warning('您没有权限查看此位置的用户权限')
    router.push('/dashboard/home')
    return;
  }
  
  // 构建URL确保位置ID被正确添加
  const baseUrl = '/dashboard/home';
  const url = locationId ? `${baseUrl}?locationId=${encodeURIComponent(String(locationId))}` : baseUrl;
  console.log('准备跳转到URL:', url);
  
  // 使用window.location.href强制刷新页面，确保所有组件都能感知位置变化
  window.location.href = url;
  
  console.log('位置已切换到:', locationId)
}

// 点击外部关闭
const closeLocationSelector = (event) => {
  const selector = document.querySelector('.sidebar-location-selector')
  if (selector && !selector.contains(event.target)) {
    showLocationSelector.value = false
  }
}
// --- 位置选择器状态结束 ---

// 用于刷新消息的函数
const refreshNotifications = async () => {
  try {
    console.log('尝试刷新消息列表...');
    let userId = userStore.getUser?.id;

    if (!userId) {
      try {
        const userJson = localStorage.getItem('user');
        if (userJson && userJson !== 'undefined') {
          const userData = JSON.parse(userJson);
          userId = userData?.id;
        }
      } catch (error) {
        console.error('从localStorage获取用户ID失败 (refreshNotifications):', error);
      }
    }

    if (userId) {
      console.log('刷新消息列表，用户ID:', userId);
      await notificationStore.fetchNotifications(userId); // 显式传递userId
      console.log('消息列表已刷新');
    } else {
      console.warn('无法获取用户ID，未能刷新消息列表。');
      // 可以选择是否在这里提示用户，例如 ElMessage.warning('请先登录以查看通知');
    }
  } catch (error) {
    console.error('刷新消息列表失败:', error);
  }
}

// 监听路由变化以更新activeMenu
watch(() => router.currentRoute.value.path, (newPath) => {
  if (newPath.includes('/dashboard/')) {
    activeMenu.value = newPath.split('/dashboard/')[1].split('/')[0]
    
    // 如果从设置页面返回，刷新位置列表
    if (newPath.includes('/dashboard/') && !newPath.includes('/dashboard/settings')) {
      const fromSettings = router.currentRoute.value.meta.fromSettings;
      if (fromSettings) {
        // 重置标记并刷新位置列表
        router.currentRoute.value.meta.fromSettings = false;
        fetchUserLocations();
      }
    }
    
    // 当进入消息通知页面时，刷新消息列表
    if (newPath.includes('/dashboard/notifications')) {
      refreshNotifications();
    }
  }
}, { immediate: true })

const user = computed(() => userStore.getUser)
const alertCount = computed(() => inventoryStore.getInventoryAlerts.totalAlerts)
const categories = computed(() => itemsStore.categories)
const locations = computed(() => itemsStore.locations)

// 通知相关
const unreadNotificationCount = computed(() => notificationStore.unreadCount)

// 是否显示权限管理菜单
const showPermissionsMenu = computed(() => {
  // 如果没有选择位置，不显示
  if (!selectedLocationId.value) return false
  
  // 检查用户是否有权限查看用户权限界面
  return permissionStore.canViewUserPermissions(selectedLocationId.value)
})

// 导航项数据
const navItems = computed(() => {
  const items = [
  { key: 'home', label: '主页', icon: IconMenu },
  { key: 'items', label: '物品管理', icon: Document },
  { key: 'inventory', label: '库存管理', icon: Goods },
  { key: 'statistics', label: '数据统计', icon: DataLine },
  { key: 'notifications', label: '消息通知', icon: Bell },
  ]
  
  // 根据权限动态添加用户权限菜单
  if (showPermissionsMenu.value) {
    items.push({ key: 'permissions', label: '用户权限', icon: User })
  }
  
  items.push({ key: 'settings', label: '系统设置', icon: Setting })
  
  return items
})

// 颜色变换判断是否为深色模式
const isDarkMode = ref(window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches)

// 监听系统颜色模式变化
onMounted(async () => {
  const currentPath = router.currentRoute.value.path
  if (currentPath.includes('/dashboard/')) {
    activeMenu.value = currentPath.split('/dashboard/')[1]
  }
  
  console.log('组件挂载，用户状态:', userStore.isLoggedIn)
  
  let userId = null;
  // 确保用户已经登录
  if (!userStore.isLoggedIn) {
    console.log('用户未登录，尝试从localStorage恢复状态')
    // 如果未登录但localStorage有token，尝试恢复状态
    const token = localStorage.getItem('token')
    if (token) {
      try {
        await userStore.getCurrentUser()
        console.log('用户状态已恢复:', userStore.getUser)
        if (userStore.getUser?.id) {
          userId = userStore.getUser.id;
        }
      } catch (error) {
        console.error('恢复用户状态失败:', error)
      }
    }
  } else if (userStore.getUser?.id) {
    userId = userStore.getUser.id;
  }
  
  // 尝试从localStorage直接获取用户ID作为备选
  if (!userId) {
    try {
      const userInfo = localStorage.getItem('user');
      if (userInfo && userInfo !== 'undefined') {
        const parsedUser = JSON.parse(userInfo);
        if (parsedUser?.id) {
          userId = parsedUser.id;
          console.log('从localStorage获取到用户ID:', userId);
        }
      }
    } catch (error) {
      console.error('解析localStorage中的user信息失败:', error);
    }
  }
  
  // 获取用户位置权限
  if (userId) {
    try {
      console.log('准备获取用户位置权限，用户ID:', userId);
      const permissionsResponse = await locationsApi.getUserLocationPermissions(userId);
      
      console.log('用户位置权限API响应:', permissionsResponse);
      
      if (permissionsResponse && permissionsResponse.code === 200 && permissionsResponse.data) {
        console.log('用户位置权限数据:', permissionsResponse.data);
        permissionStore.setUserLocationPermissions(permissionsResponse.data);
      } else {
        console.warn('获取用户位置权限失败:', permissionsResponse);
      }
    } catch (error) {
      console.error('获取用户位置权限出错:', error);
    }
  } else {
    console.error('无法获取用户ID，跳过权限获取');
  }
  
  // 获取用户位置
  console.log('准备获取用户位置');
  await fetchUserLocations();
  
  // 获取最新消息和通知
  await refreshNotifications();
  
  // 监听系统颜色模式变化
  window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) => {
    isDarkMode.value = e.matches;
  });

  // 添加全局点击监听 (位置选择器)
  document.addEventListener('click', closeLocationSelector);
});

// 移除全局点击监听 (位置选择器)
onBeforeUnmount(() => {
  document.removeEventListener('click', closeLocationSelector)
})

const handleMenuSelect = (key) => {
  if (key === 'settings') {
    // 设置一个标记，表示用户正在访问设置页面
    router.currentRoute.value.meta.fromSettings = true;
  }
  
  if (key === 'home') {
    router.push('/dashboard/home')
  } else if (key === 'items') {
    router.push('/dashboard/items')
  } else if (key === 'inventory') {
    router.push('/dashboard/inventory')
  } else if (key === 'statistics') {
    router.push('/dashboard/statistics')
  } else if (key === 'notifications') {
    router.push('/dashboard/notifications')
  } else if (key === 'permissions') {
    // 用户点击权限菜单项时，navItems计算属性已经确保了只有有权限的用户才能看到此菜单
    // 因此这里直接获取用户数据，无需再次检查权限
    
    // 获取位置的所有用户
    permissionStore.setLoading(true)
    locationsApi.getLocationUsers(selectedLocationId.value)
      .then(response => {
        console.log('获取位置用户权限响应:', response)
        if (response && response.code === 200) {
          // 将位置用户数据存储到permissionStore
          permissionStore.setLocationUsers(response.data, selectedLocationId.value)
        } else {
          ElMessage.warning('获取用户权限信息失败')
          permissionStore.clearLocationUsers()
        }
      })
      .catch(error => {
        console.error('获取位置用户权限出错:', error)
        ElMessage.error('无法连接到服务器，获取用户权限信息失败')
        permissionStore.clearLocationUsers()
      })
      .finally(() => {
        permissionStore.setLoading(false)
      })
    
    router.push('/dashboard/permissions')
  } else if (key === 'settings') {
    router.push('/dashboard/settings')
  }
}

const toggleSidebar = () => {
  isCollapse.value = !isCollapse.value
}

const toggleDetails = (item = null) => {
  if (item) {
    selectedItem.value = item
    showDetails.value = true
  } else {
    showDetails.value = !showDetails.value
  }
}

const logout = async () => {
  userStore.logout()
  router.push('/login')
}

// 监听位置变化，检查权限
watch(selectedLocationId, (newLocationId) => {
  if (newLocationId) {
    const userPermission = permissionStore.getUserRoleForLocation(newLocationId);
    console.log(`位置 ${newLocationId} 的用户权限:`, userPermission);
    console.log(`用户是否可以管理此位置:`, permissionStore.canManageLocationUsers(newLocationId));
  }
})

// 添加新位置方法
const addNewLocation = async () => {
  try {
    // 关闭位置选择器下拉菜单
    showLocationSelector.value = false;

    // 使用Element Plus对话框获取输入
    const { value: locationName } = await ElMessageBox.prompt(
      '请输入新位置名称',
      '添加位置',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /\S+/,
        inputErrorMessage: '位置名称不能为空'
      }
    );

    if (locationName) {
      // 显示加载状态
      locationsLoading.value = true;
      
      // 获取当前用户ID
      let userId = userStore.user?.userId || userStore.getUser?.id;
      
      if (!userId) {
        // 如果从store获取不到，尝试从localStorage获取
        try {
          const userJson = localStorage.getItem('user');
          if (userJson && userJson !== 'undefined') {
            const userData = JSON.parse(userJson);
            userId = userData.id || userData.userId;
          }
        } catch (err) {
          console.error('解析localStorage中的用户信息失败', err);
        }
      }
      
      if (!userId) {
        ElMessage.error('未能获取用户信息，请重新登录');
        locationsLoading.value = false;
        return;
      }
      
      // 简化请求参数，只发送位置名称
      const response = await locationsApi.createLocation({
        name: locationName
      }, userId);
      
      console.log('添加位置响应:', response, '参数:', { name: locationName, userId });
      
      if (response && response.code === 200 && response.data) {
        ElMessage.success('新位置添加成功');
        
        // 重新获取用户位置
        await fetchUserLocations();
        
        // 立即选择新添加的位置
        const newLocationId = response.data.id;
        selectLocation(newLocationId);
        
        // 刷新页面以触发位置权限请求
        window.location.reload();
      } else {
        ElMessage.error('添加位置失败: ' + (response?.msg || '未知错误'));
      }
    }
  } catch (error) {
    // 用户取消或发生错误
    if (error !== 'cancel') {
      console.error('添加位置失败:', error);
      ElMessage.error('添加位置失败: ' + (error.message || '未知错误'));
    }
  } finally {
    locationsLoading.value = false;
  }
};

// 监听位置数据变化，确保位置选择器正确显示
watch([appLocations, selectedLocationId], ([newLocations, newLocationId]) => {
  console.log('位置数据或选中位置ID变化:', {
    locations: newLocations?.length || 0,
    selectedId: newLocationId,
    currentLocationName: currentLocationName.value
  });
  
  // 如果有位置ID但没有选中的位置名称，说明可能数据同步有问题，尝试修复
  if (newLocationId && !currentLocationName.value && newLocations.length > 0) {
    console.log('检测到位置ID但没有对应位置名称，尝试修复...');
    // 查找并设置对应的位置
    const location = newLocations.find(l => l.id == newLocationId);
    if (location) {
      console.log('找到匹配的位置:', location.name);
      // 直接设置选中的位置，触发computed重新计算
      selectedLocationId.value = location.id;
    } else {
      console.warn('无法在当前位置列表中找到ID为', newLocationId, '的位置');
    }
  }
}, { deep: true });
</script>

<template>
  <div class="apple-layout-container" :class="{ 'dark-mode': isDarkMode }">
    <!-- 侧边栏 -->
    <aside class="apple-sidebar glass-effect" :class="{ 'collapsed': isCollapse }">
      <!-- 顶部位置选择器 -->
      <div class="sidebar-header sidebar-location-selector">
        <!-- 收起/展开按钮 -->
        <button @click="toggleSidebar" class="collapse-button">
          <el-icon v-if="!isCollapse"><ArrowLeft /></el-icon>
          <el-icon v-else><ArrowRight /></el-icon>
        </button>
        <!-- 位置选择器按钮 -->
        <div class="location-button" @click.stop="toggleLocationSelector">
          <el-icon><Location /></el-icon>
          <span v-show="!isCollapse">{{ currentLocationName }}</span>
          <el-icon v-show="!isCollapse" class="arrow-icon" :class="{ 'rotate': showLocationSelector }"><ArrowDown /></el-icon>
        </div>
        
        <!-- 位置下拉菜单 -->
        <transition name="dropdown">
          <div v-if="showLocationSelector && !isCollapse" class="location-dropdown">
            <!-- 加载中状态 -->
            <div v-if="locationsLoading" class="location-loading">
              <div class="loading-spinner"></div>
              <span>加载位置信息...</span>
            </div>
            <!-- 空数据状态 -->
            <div v-else-if="appLocations.length === 0" class="location-empty">
              <span>暂无位置信息</span>
            </div>
            <!-- 位置列表 -->
            <div 
              v-else
              v-for="location in appLocations" 
              :key="location.id"
              class="location-item"
              :class="{ active: selectedLocationId === location.id }"
              @click="selectLocation(location.id)"
            >
              {{ location.name }}
            </div>
            <!-- 添加位置按钮 -->
            <div class="location-item add-location" @click="addNewLocation">
              <el-icon><Plus /></el-icon>
              <span>添加位置</span>
            </div>
          </div>
        </transition>
      </div>
      
      <!-- 主导航 -->
      <div class="apple-nav">
        <div 
          v-for="(item, index) in navItems" 
          :key="item.key"
          class="apple-nav-item hover-card" 
          :class="{ 'active': activeMenu === item.key }"
          @click="handleMenuSelect(item.key)"
          :style="{ animationDelay: `${index * 0.05}s` }"
        >
          <div class="nav-icon">
            <el-icon><component :is="item.icon" /></el-icon>
          </div>
          <transition name="fade">
            <span v-show="!isCollapse" class="nav-text">{{ item.label }}</span>
          </transition>
          <el-badge v-if="item.key === 'notifications' && unreadNotificationCount > 0" :value="unreadNotificationCount" class="notification-badge" />
        </div>
      </div>
      
    </aside>
    
    <!-- 内容区域 -->
    <main class="apple-content">
      <div class="apple-content-body">
        <router-view v-slot="{ Component }">
          <transition name="fade" mode="out-in">
            <component :is="Component" @select-item="toggleDetails" />
          </transition>
        </router-view>
      </div>
    </main>
    
    <!-- 详情面板 -->
    <transition name="slide-left">
      <aside v-if="showDetails" class="apple-details glass-effect">
        <div class="details-header">
          <h3>物品详情</h3>
          <button @click="toggleDetails()" class="apple-button apple-button-icon button-float">
            <el-icon><Close /></el-icon>
          </button>
        </div>
        
        <template v-if="selectedItem">
          <div class="details-content">
            <div 
              class="item-detail-image hover-card" 
              :style="{ backgroundImage: `url(/placeholder.jpg)` }"
            ></div>
            
            <transition-group name="float-up" tag="div" class="item-detail-info">
              <h2 :key="'title'" class="item-title">{{ selectedItem.name }}</h2>
              
              <div :key="'category'" class="info-row">
                <span class="info-label">分类:</span>
                <span class="info-value">{{ itemsStore.getCategoryName(selectedItem.categoryId) }}</span>
              </div>
              
              <div :key="'location'" class="info-row">
                <span class="info-label">位置:</span>
                <span class="info-value">{{ selectedItem.location }}</span>
              </div>
              
              <div :key="'quantity'" class="info-row">
                <span class="info-label">数量:</span>
                <span class="info-value">{{ selectedItem.quantity }}</span>
              </div>
              
              <div :key="'purchase-date'" class="info-row">
                <span class="info-label">购买日期:</span>
                <span class="info-value">{{ selectedItem.purchaseDate }}</span>
              </div>
              
              <div v-if="selectedItem.expiryDate" :key="'expiry-date'" class="info-row">
                <span class="info-label">过期日期:</span>
                <span class="info-value">{{ selectedItem.expiryDate }}</span>
              </div>
              
              <div v-if="selectedItem.notes" :key="'notes'" class="info-row notes">
                <span class="info-label">备注:</span>
                <span class="info-value">{{ selectedItem.notes }}</span>
              </div>
            </transition-group>
          </div>
          
          <div class="details-actions">
            <button class="apple-button apple-button-primary button-float">编辑</button>
            <button class="apple-button apple-button-danger button-float">删除</button>
          </div>
        </template>
      </aside>
    </transition>
  </div>
</template>

<style scoped>
.apple-layout-container {
  display: flex;
  width: 100%;
  height: 100vh;
  overflow: hidden;
  background-color: var(--apple-background-light);
  color: var(--apple-text-primary-light);
  transition: background-color var(--animation-speed-medium), color var(--animation-speed-medium);
}

.dark-mode {
  background-color: var(--apple-background-dark);
  color: var(--apple-text-primary-dark);
}

/* 侧边栏样式 */
.apple-sidebar {
  width: 240px;
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: rgba(255, 255, 255, 0.9);
  border-right: 1px solid var(--apple-border-light);
  transition: all 0.4s cubic-bezier(0.34, 1.56, 0.64, 1); /* 调整过渡效果为更平滑的曲线 */
  overflow: visible; /* 改为visible以显示下拉菜单 */
  z-index: 100;
}

.dark-mode .apple-sidebar {
  background-color: rgba(44, 44, 46, 0.9);
  border-right: 1px solid var(--apple-border-dark);
}

.apple-sidebar.collapsed {
  width: 72px;
  overflow: hidden; /* 收起时隐藏 */
}

/* 侧边栏头部过渡 */
.sidebar-header {
  height: auto; /* 自适应高度 */
  display: flex;
  align-items: center;
  justify-content: space-between; /* 改为space-between以便按钮两侧分布 */
  padding: 16px 16px 0 16px; /* 调整顶部内边距，留出空间 */
  margin-bottom: 15px; /* 减小与其他元素的间距 */
  position: relative; 
  transition: all 0.3s cubic-bezier(0.34, 1.56, 0.64, 1); /* 添加过渡效果 */
}

.apple-sidebar.collapsed .sidebar-header {
  justify-content: center;
  flex-direction: column; /* 改为纵向排列 */
  align-items: center;
  transition-delay: 0.05s; /* 稍微延迟头部变化 */
}

/* 调整折叠按钮过渡 */
.collapse-button {
  position: static; /* 从绝对定位改为静态定位 */
  width: 46px; /* 调整宽度与高度匹配位置选择器按钮 */
  height: 46px;
  border-radius: var(--button-border-radius, 23px);
  background-color: var(--apple-button-light);
  border: 1px solid var(--apple-border-light);
  box-shadow: 0 1px 2px rgba(0,0,0,0.03);
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  z-index: 102;
  transition: all 0.3s cubic-bezier(0.34, 1.56, 0.64, 1); /* 匹配侧边栏过渡 */
  margin-top: 10px; /* 与位置选择器按钮对齐 */
}

/* 位置选择器按钮过渡 */
.sidebar-location-selector .location-button {
  width: 70%; /* 修改为较大宽度 */
  display: flex;
  align-items: center;
  gap: 10px; 
  background-color: var(--apple-button-light); /* 添加浅色背景 */
  border: 1px solid var(--apple-border-light); /* 添加细边框 */
  border-radius: var(--button-border-radius, 23px); 
  padding: 10px 16px; /* 调整内边距 */
  font-size: 15px; /* 稍微减小字体 */
  font-weight: 500; 
  box-shadow: 0 1px 2px rgba(0,0,0,0.03); /* 添加细微阴影 */
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.34, 1.56, 0.64, 1); /* 匹配侧边栏过渡 */
  color: var(--apple-text-primary-light);
  justify-content: flex-start;
  height: auto; /* 高度自适应 */
  margin-top: 10px; /* 向下移动 */
  will-change: transform, width; /* 优化性能 */
}

.apple-sidebar.collapsed .sidebar-location-selector .location-button {
  padding: 10px;
  justify-content: center;
  height: 46px; /* 保持高度一致 */
  width: 46px; /* 收起时变为方形 */
  margin-top: 10px; /* 收起时与折叠按钮保持距离 */
  transition-delay: 0.05s; /* 添加微小延迟 */
}

/* 导航项过渡效果 */
.apple-nav-item {
  height: 46px;
  border-radius: var(--button-border-radius, 23px); /* 确保导航项也使用变量 */
  display: flex;
  align-items: center;
  padding: 0 16px;
  cursor: pointer;
  position: relative;
  color: var(--apple-text-primary-light);
  transition: all 0.3s cubic-bezier(0.34, 1.56, 0.64, 1); /* 匹配侧边栏过渡 */
  animation: float-up var(--animation-speed-medium) forwards;
  opacity: 0;
  overflow: hidden;
  will-change: transform, padding; /* 优化性能 */
}

.apple-sidebar.collapsed .apple-nav-item {
  justify-content: center;
  padding: 0;
  transition-delay: 0.05s; /* 添加微小延迟 */
}

.nav-icon {
  font-size: 18px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 12px;
  transition: all 0.3s cubic-bezier(0.34, 1.56, 0.64, 1); /* 匹配侧边栏过渡 */
}

.apple-sidebar.collapsed .nav-icon {
  margin-right: 0;
  font-size: 20px;
  transition-delay: 0.1s; /* 图标稍微滞后变化 */
}

/* 添加文本淡入淡出效果 */
.nav-text {
  flex: 1;
  white-space: nowrap;
  font-weight: 500;
  font-size: 16px; /* 确保导航文字大小一致 */
  transition: opacity 0.2s ease, transform 0.3s cubic-bezier(0.34, 1.56, 0.64, 1); /* 添加文本过渡 */
  transform-origin: left center;
}

.apple-sidebar.collapsed .nav-text {
  opacity: 0;
  transform: translateX(-10px) scale(0.9);
  transition: opacity 0.15s ease, transform 0.2s ease; /* 收起时更快的消失动画 */
}

/* 添加下拉菜单的过渡效果 */
.dropdown-enter-active, .dropdown-leave-active {
  transition: opacity 0.25s ease, transform 0.25s cubic-bezier(0.34, 1.56, 0.64, 1);
  transform-origin: top center;
}

.dropdown-enter-from, .dropdown-leave-to {
  opacity: 0;
  transform: translateY(-10px) scale(0.95);
}

/* 为淡入淡出添加过渡效果 */
.fade-enter-active, .fade-leave-active {
  transition: opacity 0.25s ease, transform 0.25s cubic-bezier(0.34, 1.56, 0.64, 1);
}

.fade-enter-from, .fade-leave-to {
  opacity: 0;
  transform: translateY(5px);
}

/* 导航样式 */
.apple-nav {
  display: flex;
  flex-direction: column;
  gap: 12px;
  padding: 0 16px;
  margin-bottom: 32px;
}

.apple-nav-item {
  height: 46px;
  border-radius: var(--button-border-radius, 23px); /* 确保导航项也使用变量 */
  display: flex;
  align-items: center;
  padding: 0 16px;
  cursor: pointer;
  position: relative;
  color: var(--apple-text-primary-light);
  transition: all 0.3s cubic-bezier(0.34, 1.56, 0.64, 1); /* 匹配侧边栏过渡 */
  animation: float-up var(--animation-speed-medium) forwards;
  opacity: 0;
  overflow: hidden;
}

.apple-nav-item::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
  transition: 0.5s;
}

.apple-nav-item:hover::before {
  left: 100%;
}

.dark-mode .apple-nav-item {
  color: var(--apple-text-primary-dark);
}

@keyframes float-up {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.apple-nav-item:hover {
  background-color: rgba(0, 122, 255, 0.1);
  transform: translateY(-2px);
  box-shadow: var(--shadow-sm);
}

.apple-nav-item.active {
  background: linear-gradient(135deg, var(--apple-blue), #0062cc);
  color: white;
  box-shadow: 0 4px 12px rgba(0, 122, 255, 0.3);
}

.dark-mode .apple-nav-item.active {
  background: linear-gradient(135deg, var(--apple-blue-dark), #0A84FF);
  box-shadow: 0 4px 12px rgba(10, 132, 255, 0.3);
}

.nav-icon {
  font-size: 18px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 12px;
  transition: all 0.3s cubic-bezier(0.34, 1.56, 0.64, 1); /* 匹配侧边栏过渡 */
}

.apple-nav-item:hover .nav-icon {
  transform: scale(1.1);
}

.apple-sidebar.collapsed .nav-icon {
  margin-right: 0;
  font-size: 20px;
  transition-delay: 0.1s; /* 图标稍微滞后变化 */
}

.apple-sidebar.collapsed .apple-nav-item {
  justify-content: center;
  padding: 0;
  transition-delay: 0.05s; /* 添加微小延迟 */
}

.nav-text {
  flex: 1;
  white-space: nowrap;
  font-weight: 500;
  font-size: 16px; /* 确保导航文字大小一致 */
  transition: opacity 0.2s ease, transform 0.3s cubic-bezier(0.34, 1.56, 0.64, 1); /* 添加文本过渡 */
  transform-origin: left center;
}

.notification-badge {
  margin-left: 8px;
}

/* 添加折叠状态下的通知徽章样式 */
.apple-sidebar.collapsed .notification-badge {
  position: absolute;
  top: -2px;
  right: 14px;
  transform: scale(0.9);
}

/* 调整通知徽章的样式，使其与图片中的更一致 */
.el-badge__content {
  background-color: var(--apple-red, #FF3B30);
  border: none;
  color: white;
  font-size: 12px;
  font-weight: 600;
  min-width: 18px;
  height: 18px;
  line-height: 18px;
  border-radius: 9px;
  padding: 0 5px;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 2px 4px rgba(255, 59, 48, 0.3);
}

.dark-mode .el-badge__content {
  background-color: var(--apple-red-dark, #FF453A);
  box-shadow: 0 2px 4px rgba(255, 69, 58, 0.3);
}

/* 过滤器样式 */
.apple-filters {
  padding: 0 16px;
  margin-bottom: 32px;
}

.apple-filters h3 {
  font-size: 14px;
  font-weight: 600;
  margin-bottom: 12px;
  color: var(--apple-text-secondary-light);
}

.dark-mode .apple-filters h3 {
  color: var(--apple-text-secondary-dark);
}

.apple-filter-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
  margin-bottom: 24px;
}

.apple-filter-item {
  height: 38px;
  border-radius: var(--button-border-radius);
  background-color: var(--apple-button-light);
  display: flex;
  align-items: center;
  padding: 0 12px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all var(--animation-speed-fast) cubic-bezier(0.33, 1, 0.68, 1);
  animation: float-up var(--animation-speed-medium) forwards;
  opacity: 0;
  position: relative;
  overflow: hidden;
}

.apple-filter-item::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
  transition: 0.5s;
}

.apple-filter-item:hover::before {
  left: 100%;
}

.dark-mode .apple-filter-item {
  background-color: var(--apple-button-dark);
}

.apple-filter-item:hover {
  background-color: rgba(0, 122, 255, 0.1);
  transform: translateY(-2px);
  box-shadow: var(--shadow-sm);
}

.dark-mode .apple-filter-item:hover {
  background-color: rgba(10, 132, 255, 0.1);
  box-shadow: var(--shadow-sm-dark);
}

/* 删除侧边栏切换按钮样式 */
.sidebar-toggle {
  display: none;
}

/* 内容区域样式 */
.apple-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow: hidden;
}

.apple-content-body {
  flex: 1;
  overflow-y: auto;
  padding: 24px;
  position: relative;
}

/* 详情面板样式 */
.apple-details {
  width: 320px;
  height: 100%;
  background-color: rgba(255, 255, 255, 0.9);
  border-left: 1px solid var(--apple-border-light);
  display: flex;
  flex-direction: column;
  overflow: hidden;
  z-index: 50;
}

.dark-mode .apple-details {
  background-color: rgba(44, 44, 46, 0.9);
  border-left: 1px solid var(--apple-border-dark);
}

.details-header {
  height: 64px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 24px;
  border-bottom: 1px solid var(--apple-border-light);
}

.dark-mode .details-header {
  border-bottom: 1px solid var(--apple-border-dark);
}

.details-content {
  flex: 1;
  padding: 24px;
  overflow-y: auto;
}

.item-detail-image {
  width: 100%;
  height: 180px;
  border-radius: var(--card-border-radius);
  background-size: cover;
  background-position: center;
  margin-bottom: 24px;
  transition: transform var(--animation-speed-fast), box-shadow var(--animation-speed-fast);
}

.item-title {
  font-size: 24px;
  font-weight: 600;
  margin-bottom: 16px;
}

.info-row {
  margin-bottom: 12px;
  animation: float-up var(--animation-speed-medium) forwards;
  opacity: 0;
}

.info-label {
  font-size: 14px;
  color: var(--apple-text-secondary-light);
  margin-bottom: 4px;
  display: block;
}

.dark-mode .info-label {
  color: var(--apple-text-secondary-dark);
}

.info-value {
  font-size: 16px;
}

.info-row.notes {
  margin-top: 16px;
}

.details-actions {
  padding: 24px;
  display: flex;
  gap: 12px;
  border-top: 1px solid var(--apple-border-light);
}

.dark-mode .details-actions {
  border-top: 1px solid var(--apple-border-dark);
}

/* 按钮样式 */
.apple-button {
  border: none;
  padding: 8px 16px;
  border-radius: var(--button-border-radius);
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: background-color var(--animation-speed-fast), 
              color var(--animation-speed-fast),
              transform var(--animation-speed-fast),
              box-shadow var(--animation-speed-fast);
}

.apple-button-text {
  background-color: transparent;
  color: var(--apple-blue);
}

.dark-mode .apple-button-text {
  color: var(--apple-blue-dark);
}

.apple-button-icon {
  width: 36px;
  height: 36px;
  padding: 0;
  background-color: var(--apple-button-light);
  color: var(--apple-text-primary-light);
}

.dark-mode .apple-button-icon {
  background-color: var(--apple-button-dark);
  color: var(--apple-text-primary-dark);
}

.apple-button-primary {
  background-color: var(--apple-blue);
  color: white;
}

.dark-mode .apple-button-primary {
  background-color: var(--apple-blue-dark);
}

.apple-button-danger {
  background-color: var(--apple-red);
  color: white;
}

.dark-mode .apple-button-danger {
  background-color: var(--apple-red-dark);
}

.apple-button .el-icon {
  margin-right: 6px;
}

.apple-button-icon .el-icon {
  margin-right: 0;
}

/* 响应式适配 */
@media (max-width: 768px) {
  .apple-sidebar {
    position: fixed;
    left: 0;
    top: 0;
    bottom: 0;
    transform: translateX(-100%);
    z-index: 1000;
    width: 80%;
    max-width: 300px;
    box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
  }
  
  .dark-mode .apple-sidebar {
    box-shadow: 0 0 20px rgba(0, 0, 0, 0.3);
  }
  
  .apple-sidebar.collapsed {
    width: 72px;
    transform: translateX(0);
  }
  
  .apple-sidebar:not(.collapsed) {
    transform: translateX(0);
  }
  
  .apple-details {
    position: fixed;
    right: 0;
    top: 0;
    bottom: 0;
    width: 90%;
    max-width: 350px;
    box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
  }
  
  .dark-mode .apple-details {
    box-shadow: 0 0 20px rgba(0, 0, 0, 0.3);
  }
}

.apple-sidebar.collapsed .collapse-button {
  margin-left: 0; /* 移除左边距 */
  width: 46px; /* 与位置按钮同宽 */
  height: 46px; /* 确保高度一致 */
  padding: 0;
  margin-top: 10px; /* 设置顶部边距 */
  margin-bottom: 10px; /* 添加下边距 */
  transition-delay: 0.05s; /* 添加过渡延迟 */
}

/* --- 位置选择器样式 --- */
.dark-mode .sidebar-location-selector .location-button {
  color: var(--apple-text-primary-dark);
  background-color: var(--apple-button-dark); /* 深色模式背景 */
  border: 1px solid var(--apple-border-dark);
  box-shadow: 0 1px 2px rgba(0,0,0,0.1); 
}

.sidebar-location-selector .location-button .el-icon:first-child {
  font-size: 18px;
}

.sidebar-location-selector .location-button:hover {
  background-color: var(--apple-button-light-hover); /* 悬停背景 */
  border-color: var(--apple-border-light-hover);
  box-shadow: 0 2px 5px rgba(0,0,0,0.05); /* 悬停阴影 */
  transform: translateY(-1px); /* 悬停上浮 */
}

.dark-mode .sidebar-location-selector .location-button:hover {
  background-color: var(--apple-button-dark-hover);
  border-color: var(--apple-border-dark-hover);
   box-shadow: 0 2px 5px rgba(0,0,0,0.15);
}

.sidebar-location-selector .location-button:active {
   transform: translateY(0); /* 点击效果 */
  box-shadow: 0 1px 2px rgba(0,0,0,0.03);
   transition-duration: 0.05s;
}

.dark-mode .sidebar-location-selector .location-button:active {
   box-shadow: 0 1px 2px rgba(0,0,0,0.1);
}

.apple-sidebar.collapsed .sidebar-location-selector .location-button span,
.apple-sidebar.collapsed .sidebar-location-selector .location-button .arrow-icon {
  display: none;
  transition: opacity 0.15s ease;
  opacity: 0;
}

.sidebar-location-selector .arrow-icon {
  font-size: 12px;
  margin-left: auto; /* 推到最右侧 */
  transition: transform 0.3s;
}

.sidebar-location-selector .arrow-icon.rotate {
  transform: rotate(180deg);
}

.sidebar-location-selector .location-dropdown {
  position: absolute;
  top: calc(100% - 8px); /* 调整顶部位置，让它更紧贴按钮 */
  left: 70px; /* 对齐左侧按钮位置 */
  width: 70%; /* 与位置按钮宽度一致 */
  background-color: rgba(255, 255, 255, 0.95);
  border-radius: 12px; /* 统一圆角 */
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  z-index: 100;
  max-height: 250px; /* 减小最大高度 */
  overflow-y: auto;
  margin-top: 8px; /* 添加与按钮的间距 */
  border: 1px solid var(--apple-border-light); /* 添加边框 */
}

.dark-mode .sidebar-location-selector .location-dropdown {
  background-color: rgba(50, 50, 55, 0.95);
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
  border: 1px solid var(--apple-border-dark);
}

.location-item {
  padding: 10px 14px; /* 减小内边距 */
  cursor: pointer;
  transition: background-color 0.2s ease;
  font-size: 14px; /* 减小字体大小 */
}

.location-item:hover {
  background-color: rgba(0, 0, 0, 0.05);
}

.dark-mode .location-item:hover {
  background-color: rgba(255, 255, 255, 0.1);
}

.location-item.active {
  background-color: rgba(0, 122, 255, 0.1);
  color: #007aff;
}

.dark-mode .location-item.active {
  background-color: rgba(10, 132, 255, 0.2);
  color: #0a84ff;
}

/* 添加位置按钮样式 */
.location-item.add-location {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  border-top: 1px solid var(--apple-border-light);
  color: #007aff;
  font-weight: 500;
  padding: 12px;
}

.dark-mode .location-item.add-location {
  border-top: 1px solid var(--apple-border-dark);
  color: #0a84ff;
}

.location-item.add-location:hover {
  background-color: rgba(0, 122, 255, 0.05);
}

.dark-mode .location-item.add-location:hover {
  background-color: rgba(10, 132, 255, 0.1);
}

/* 加载状态样式 */
.location-loading, .location-empty {
  padding: 12px; /* 减小内边距 */
  text-align: center;
  color: #86868b;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 60px; /* 减小最小高度 */
  font-size: 14px; /* 减小字体大小 */
}

.loading-spinner {
  width: 20px; /* 减小加载图标大小 */
  height: 20px;
  border: 2px solid rgba(0, 122, 255, 0.1);
  border-top-color: #007aff;
  border-radius: 50%;
  animation: spin 1s infinite linear;
  margin-bottom: 6px; /* 减小下边距 */
}

.dark-mode .loading-spinner {
  border: 2px solid rgba(10, 132, 255, 0.1);
  border-top-color: #0a84ff;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 折叠按钮的暗黑模式 */
.dark-mode .collapse-button {
  background-color: var(--apple-button-dark);
  border: 1px solid var(--apple-border-dark);
  box-shadow: 0 1px 3px rgba(0,0,0,0.2);
}

.collapse-button:hover {
  background-color: var(--apple-button-light-hover);
  border-color: var(--apple-border-light-hover);
  box-shadow: 0 2px 5px rgba(0,0,0,0.05);
  transform: translateY(-1px);
}

.dark-mode .collapse-button:hover {
  background-color: var(--apple-button-dark-hover);
  border-color: var(--apple-border-dark-hover);
  box-shadow: 0 2px 5px rgba(0,0,0,0.15);
}

.collapse-button:active {
  transform: translateY(0);
  box-shadow: 0 1px 2px rgba(0,0,0,0.03);
  transition-duration: 0.05s;
}

/* 添加通知图标样式 */
.header-notification {
  margin-left: auto;
  margin-right: 8px;
  display: flex;
  align-items: center;
}

.apple-sidebar.collapsed .header-notification {
  display: none;
}
</style> 